package cc.rengu.igas.momp.common.util;

import cc.rengu.jrbdp.register.realtime.client.RealTimeRegisterClient;
import cc.rengu.utility.log.RgLogger;

/**
 * @author xu
 */
public class RbdpClient {

    private static RealTimeRegisterClient client;

    public static RealTimeRegisterClient getIntance1(RgLogger rglog, String rbdpserver) {
        try {
            if (client == null) {
                client = new RealTimeRegisterClient();
                register(rglog, rbdpserver);
            }
            boolean isconnect = client.connect();
            if (!isconnect) {
                String error = client.getError();
                rglog.error("实时注册服务器连接异常:[" + error + "]");
            }
        } catch (Exception e) {
            rglog.error("实时注册服务器连接异常:[" + e.getMessage() + "]");
        }
        return client;
    }

    private static void register(RgLogger rglog, String rbdpserver) {
        int id = 0;
        String[] serverList = rbdpserver.split(",");
        for (String server : serverList) {
            String[] argArr = server.split(":");
            String ipAddr = null;
            int port = 0;
            int connectTimeout = 10000;
            int readTimeout = 10000;
            if (argArr.length >= 2) {
                ipAddr = argArr[0];
                port = Integer.parseInt(argArr[1]);
            } else {
                continue;
            }
            if (argArr.length >= 3) {
                connectTimeout = Integer.parseInt(argArr[2]);
            }
            if (argArr.length >= 4) {
                readTimeout = Integer.parseInt(argArr[3]);
            }

            rglog.info("服务器-{}: [{}:{}] 连接超时[{}], 读取超时[{}]\n", id, ipAddr, port, connectTimeout, readTimeout);
            client.addServer(ipAddr, port, connectTimeout, readTimeout);
            id++;
        }
    }
}
